<template>
  <div>
    <el-button type="primary" @click="$router.push('/create-post')"
      >新增文章</el-button
    >
    <el-table :data="articles" style="width: 100%; margin-top: 20px">
      <el-table-column label="文章标题" prop="title"></el-table-column>
      <el-table-column label="作者" prop="userName"></el-table-column>
      <el-table-column label="访问量" prop="visitNum"></el-table-column>
      <el-table-column label="点赞量" prop="thumbNum"></el-table-column>
      <el-table-column label="创作时间" prop="createTime"></el-table-column>
      <el-table-column label="最近更新" prop="updateTime"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="editArticle(row)" type="text" size="small"
            >编辑</el-button
          >
          <el-button
            @click="deleteArticle(row.id)"
            type="text"
            size="small"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      articles: [], // 文章数据
      newArticle: {
        // 新文章数据
        title: "",
        content: "",
      },
    };
  },
  created() {
    this.fetchArticles();
  },
  methods: {
    async fetchArticles() {
      const response = await request.get("/forum/selectAll", {
        params: {
          page: 1, // 当前页
          size: 99999, // 每页显示的帖子数
        },
      });
      this.articles = response.data;
    },
    editArticle(article) {
      // 跳转到 /create-post 页面并传递参数
      this.$router.push({
        path: "/create-post",
        query: {
          mode: "edit", // 用于区分是编辑还是新建
          id: article.id,
          title: article.title,
          content: article.content,
        },
      });
    },
    async deleteArticle(postId) {
      try {
        // 弹出确认框
        const confirmDelete = await this.$confirm(
          "确认删除这篇文章吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        if (confirmDelete === "confirm") {
          // 用户确认删除，执行删除操作
          await request.delete(`/forum/delete/${postId}`);
          this.fetchArticles(); // 刷新文章列表
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("请求失败:");
        }
      }
    },
  },
};
</script>
